<template>
  <!-- 本地 SVG 图标 -->
  <svg
    v-if="!isExternal"
    class="svg-icon"
    :class="customClass"
    :style="svgStyle"
    aria-hidden="true"
    v-bind="$attrs"
  >
    <use :xlink:href="iconName" />
  </svg>

  <!-- 阿里云图标库图标 -->
  <i
    v-else
    :class="['iconfont', `${name}`, customClass]"
    :style="externalStyle"
    v-bind="$attrs"
  />
</template>

<script setup lang="ts">
import { computed } from "vue";

const props = defineProps({
  // 图标名称（本地SVG名称或阿里云图标名称）
  name: {
    type: String,
    required: true
  },
  // 图标尺寸
  size: {
    type: [String, Number],
    default: "1em"
  },
  // 图标颜色
  color: {
    type: String,
    default: "inherit"
  },
  // 自定义类名
  customClass: {
    type: String,
    default: ""
  },
  // 旋转角度
  rotate: {
    type: Number,
    default: 0
  }
});

// 判断是否为外部图标（阿里云图标）
const isExternal = computed(() => {
  return props.name.startsWith("icon-");
});

// 本地SVG图标的名称
const iconName = computed(() => `#icon-${props.name}`);

// SVG图标的样式
const svgStyle = computed(() => {
  const style = {
    fontSize: typeof props.size === "number" ? `${props.size}px` : props.size,
    color: props.color
  };

  if (props.rotate) {
    return {
      ...style,
      transform: `rotate(${props.rotate}deg)`
    };
  }

  return style;
});

// 阿里云图标的样式
const externalStyle = computed(() => {
  return {
    fontSize: typeof props.size === "number" ? `${props.size}px` : props.size,
    color: props.color,
    transform: props.rotate ? `rotate(${props.rotate}deg)` : undefined
  };
});
</script>

<style scoped>
.svg-icon {
  display: inline-block;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
  transition: transform 0.3s ease;
}

.iconfont {
  display: inline-block;
  font-style: normal;
  vertical-align: middle;
  text-align: center;
  text-transform: none;
  line-height: 1;
  transition: transform 0.3s ease;
}
</style>
